package com.talkweb.sendmsg.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Service
public class MsgSender {

	@Autowired
	RestTemplate restTemplate;

	private static final String APPKEY = "2ca1d149bcecff7b1adb49712f718d46";

	public String sendMsg() {
		String mobile = "17896442119";
		return this.sendMsg(mobile);
	}

	public String sendMsg(String mobile) {
		// http://v.juhe.cn/sms/send?mobile=手机号码&tpl_id=短信模板ID&tpl_value=%23code%23%3D654654&key=
		int tpl_id = 97318;
		// String tpl_value = "#code#=431515";
		String tpl_value = "%23code%23%3d431515";  // 默认编码: #code#=431515
		String code = String.valueOf((int) (Math.random() * 1000000));
		try {
			tpl_value = URLEncoder.encode("#code#=" + code, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		String url = "http://v.juhe.cn/sms/send?mobile=" + mobile + "&tpl_id=" + tpl_id + "&tpl_value=" + tpl_value + "&key=" + APPKEY;
		ResponseEntity<String> results = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
		String json = results.getBody();
		System.out.println(code);
		return json;
	}

}
